package top.lingkang.websocketlivechrome.ws;

/**
 * @author lingkang
 * Created by 2021/12/21
 */
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {


    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //websocket基于http协议，所以用http解码器
        pipeline.addLast(new HttpServerCodec());
        //对大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        //对httpMessage进行聚合，聚合成FullHttpRequest或者FullHttpResponse
        //几乎在所有的netty编程中，都会使用到此handler
        pipeline.addLast(new HttpObjectAggregator(1024 * 64));

        //-----------------------以上是用于支持http协议 -----------------------------------------


        //这是我们自定义的handler
        pipeline.addLast(new NettyHandler());

        /**
         * websocket 服务端处理的协议， 用于指定给客户端访问连接的路由
         * 会帮你处理握手动作：handshaking（close、ping、pong）ping + pong =心跳
         * 对于websocket来将，都是以frames进行传输的，不同类型的数据对应的frames也不同
         */
        //路径要放在最后
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
    }
}
